//Copyright FUJITSU LIMITED 2015.
/*
 * Gray Code
 * 
The gray code is a binary numeral system where two successive values differ in only one bit.

Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.

For example, given n = 2, return [0,1,3,2]. Its gray code sequence is:

00 - 0
01 - 1
11 - 3
10 - 2
Note:
For a given n, a gray code sequence is not uniquely defined.

For example, [0,2,3,1] is also a valid gray code sequence according to the above definition.

For now, the judge is able to judge based on one instance of gray code sequence. Sorry about that.
 *
 * 思路：
 *   总数为  2^n 。
 *   由小到大，检查每个可变位数是否已经存在list中。不存在则添加。
 *   
 *   算法复杂度 O(n2^n)
 *   
 *   lc上有人解法
 *   
public List<Integer> grayCode(int n) {
    List<Integer> ret = new LinkedList<Integer>();
    for (int i = 0; i < Math.pow(2,n); i++)
        ret.add(((i << 1) ^ i) >> 1);
    return ret;
}
 *     更接近数学方法
 *     复杂度 O(2^n)
 */
package com.leetcode.weicl.problems.no89;

import java.util.ArrayList;
import java.util.List;

/**
 * The Class Solution.<br>
 * 
 * @author FNST)WeiCL
 * @version 1.0
 */
public class Solution {
	void tryList(List<Integer> list, int n) {
		int now = list.get(list.size()-1);
		for (int i = 0; i < n; i++) {
			int cur = now ^ (1<<i);
			if (!list.contains(cur)) {
				list.add(cur);
				break;
			}
        }
	}
	
    public List<Integer> grayCode(int n) {
    	List<Integer> ans = new ArrayList<Integer>();
    	ans.add(0);
    	int len = 1 << n ;
    	for (int i = 0; i < len; i++) {
    		tryList(ans, n);
        }
        return ans;
    }
    
    public static void main(String[] args) {
	    Solution s = new Solution();
	    System.out.println(s.grayCode(2));
    }
}
